#include "RingQueue.hpp"

#include <unistd.h>

const int CONSUMER_NUM = 4;
const int PRODUCTOR_NUM = 2;

void* Consumer(void* args)
{                          /*这里用到了reinterpret_cast强转，不懂的同学可以点我下面给的博客*/
    RingQueue<int>* rq = reinterpret_cast<RingQueue<int>*>(args);

    // 消费者消费
    while(1)
    {
        sleep(1);
        int data;
        rq->Pop(data);
        printf("[ %lu ] consumer get data ::%d\n", pthread_self(), data);
    }
}

void* Productor(void* args)
{
    RingQueue<int>* rq = reinterpret_cast<RingQueue<int>*>(args);
    
    int data = 0;
    // 生产者生产
    while(1)
    {
        rq->Push(data);
        printf("[ %lu ] productor send data ::%d\n", pthread_self(), data);
        ++data;
    }
}

int main()
{
    RingQueue<int>* rq = new RingQueue<int>();
    
    // 创建生产者消费者线程
    pthread_t c[CONSUMER_NUM];
    pthread_t p[PRODUCTOR_NUM]; 
    for(int i = 0; i < CONSUMER_NUM; ++i)
    {
        pthread_create(c + i, nullptr, Consumer, reinterpret_cast<void*>(rq));
    }

    for(int i = 0; i < PRODUCTOR_NUM; ++i)
    {
        pthread_create(p + i, nullptr, Productor, reinterpret_cast<void*>(rq));
    }

    // 等待两个线程
    for(int i = 0; i < CONSUMER_NUM; ++i)
    {
        pthread_join(c[i], nullptr);
    }
    
    for(int i = 0; i < PRODUCTOR_NUM; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    // delete掉rq，防止内存泄漏
    delete rq;

    return 0;
}